package com.code;

import java.sql.DriverManager;
import java.util.Calendar;

import com.Global.Global;
import com.database.DBSystem;
import com.example.R;
import com.service.MyService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener {
	private static final String TAG = "ServicesDemo";
	private Button btStart, btStop, btXemThongKe, btXemBieuDo, btWifi,
			btCallHis;
	private static  TextView textView2;
	private final int REQUESTCODE_TKLOGIN = 100;
	private final int REQUESTCODE_CALLHIS = 200;
	public static final int CHOOSE_THONGKE = 101;
	public static final int CHOOSE_BIEUDO = 102;
	private int countClick = 0;
	private int second = 0;
	private int minute = 0;
	
	String strStatusServerName, dateBaseName;

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 0, 0, "Kết nối đến máy chủ khác");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0: {
			DBSystem dbcv = new DBSystem(this);
			dbcv.open();
			dbcv.UpdateRemember("0");
			dbcv.close();
			Intent intent = new Intent(Main.this, LoginConfig.class);
			startActivity(intent);
			Main.this.finish();
			break;
		}
		}
		return true;
	}

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		
		
		btStart = (Button) findViewById(R.id.btStart);
		btStop = (Button) findViewById(R.id.btStop);
		btXemThongKe = (Button) findViewById(R.id.btXemThongKe);
		btXemBieuDo = (Button) findViewById(R.id.btXemBieuDo);
		btWifi = (Button) findViewById(R.id.btWifi);
		btCallHis = (Button) findViewById(R.id.btCallHis);
		textView2 = (TextView) findViewById(R.id.textView2);
		// btTKCuocGoi = (Button) findViewById(R.id.btTKCuocGoi);

		strStatusServerName = "";
		dateBaseName = "";
		String valueText = "", dbNameToRef = "";

		DBSystem dbcv = new DBSystem(this);
		//auto conect		
		connect(dbcv);
				//
		dbcv.open();
		Cursor cur = dbcv.SelectSystemAll();
		while (cur.moveToNext()) {
			strStatusServerName = cur.getString(10);
			dateBaseName = cur.getString(5);// get database name edit by trangbm
											// date 04/04/2013
		}
		cur.close();
		dbcv.close();
		if (strStatusServerName.equals("wifi")) {
			btWifi.setText("Wifi (On)");
			btWifi.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
			// bt3G.setText("3G");
		} else {
			btWifi.setText("3G (On)");
			btWifi.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			// bt3G.setText("3G (On)");
		}

		// edit by tranng date 03/04/2014
		SharedPreferences shareFrDbName = this.getSharedPreferences("dbName",
				MODE_WORLD_WRITEABLE);
		if (shareFrDbName != null)
			dbNameToRef = shareFrDbName.getString("dataName", "");// get value
																	// to
																	// shareFrDbName
		SharedPreferences shareFr = this.getSharedPreferences("saveValueCall",
				MODE_WORLD_WRITEABLE);

		// check databseName
		if (dbNameToRef.equals(dateBaseName)) {
			if (shareFr != null) {
				valueText = shareFr.getString("iscall", "");
				btStop.setText(valueText);
			}
		}
		if (valueText.equals("Lưu cuộc gọi") || valueText.equals("")) {
			Log.d(TAG, "onClick: starting service");
			startService(new Intent(this, MyService.class));

			btStop.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
			saveValueDefaultByString("dbName", "dataName", dateBaseName);
			// save is insert call edit bya trangbm date 11/04/2014
			clearValueDefault("insert_call", 0, "isinsert");
			saveValueDefaultByString("insert_call", "isinsert", "Y");
		} else {
			Log.d(TAG, "onClick: stopping service");
			startService(new Intent(this, MyService.class));
			btStop.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			saveValueDefaultByString("dbName", "dataName", dateBaseName);
			// save is insert call edit bya trangbm date 11/04/2014
			clearValueDefault("insert_call", 0, "isinsert");
			saveValueDefaultByString("insert_call", "isinsert", "N");
		}

		// btStart.setOnClickListener(this);
		btStop.setOnClickListener(this);
		btXemThongKe.setOnClickListener(this);
		btXemBieuDo.setOnClickListener(this);
		btWifi.setOnClickListener(this);
		btCallHis.setOnClickListener(this);
		textView2.setOnClickListener(this);
		// startService(new Intent(this, MyService.class));//comment by trangbm
		// date 04/04/2014
	}

	
	public void onClick(View src) {
		switch (src.getId()) {
		// case R.id.btStart:
		// Log.d(TAG, "onClick: starting service");
		// startService(new Intent(this, MyService.class));
		// break;
		case R.id.btStop:
			if (btStop.getText().equals("Lưu cuộc gọi")) {// edit by trangbm
															// date 03/04/2014
				Log.d(TAG, "onClick: stopping service");
				// stopService(new Intent(this, MyService.class));s
				startService(new Intent(this, MyService.class));
				// MyService.insert = false;
				btStop.setText("Không lưu cuộc gọi");
				btStop.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
				clearValueDefault("saveValueCall", 0, "iscall");
				saveValueDefaultByString("saveValueCall", "iscall", btStop
						.getText().toString());
				saveValueDefaultByString("dbName", "dataName", dateBaseName);
				// save is insert call edit bya trangbm date 11/04/2014
				clearValueDefault("insert_call", 0, "isinsert");
				saveValueDefaultByString("insert_call", "isinsert", "N");
			} else {
				Log.d(TAG, "onClick: starting service");
				startService(new Intent(this, MyService.class));
				// MyService.insert = true;
				btStop.setText("Lưu cuộc gọi");
				btStop.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
				clearValueDefault("saveValueCall", 0, "iscall");
				saveValueDefaultByString("saveValueCall", "iscall", btStop
						.getText().toString());
				saveValueDefaultByString("dbName", "dataName", dateBaseName);
				// save is insert call edit bya trangbm date 11/04/2014
				clearValueDefault("insert_call", 0, "isinsert");
				saveValueDefaultByString("insert_call", "isinsert", "Y");
			}// end edit date 03/04/2014
			break;
		case R.id.btXemThongKe:
			Intent i = new Intent(Main.this, TK_Login.class);
			Bundle b = new Bundle();
			b.putInt("iChooseTKBD", CHOOSE_THONGKE);
			i.putExtras(b);
			startActivityForResult(i, REQUESTCODE_TKLOGIN);
			break;
		case R.id.btXemBieuDo:
			i = new Intent(Main.this, TK_Login.class);
			b = new Bundle();
			b.putInt("iChooseTKBD", CHOOSE_BIEUDO);
			i.putExtras(b);
			startActivityForResult(i, REQUESTCODE_TKLOGIN);
			break;
		case R.id.btWifi:
			if (strStatusServerName.equals("3g")) {
				DBSystem dbWifi = new DBSystem(this);
				dbWifi.open();
				dbWifi.UpdateStatusServerName("wifi");
				dbWifi.close();
				Global.StatusServerName = "wifi";
				strStatusServerName = "wifi";
				btWifi.setText("Wi-Fi (On)");
				btWifi.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);

			} else {
				DBSystem db3g = new DBSystem(this);
				db3g.open();
				db3g.UpdateStatusServerName("3g");
				db3g.close();
				Global.StatusServerName = "3g";
				strStatusServerName = "3g";
				btWifi.setText("3G (On)");
				btWifi.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			}
			break;
		case R.id.btCallHis:
			startActivityForResult(new Intent(Main.this, CallHistory.class),
					REQUESTCODE_CALLHIS);
			break;
		case R.id.textView2:
			Calendar cal = Calendar.getInstance();

			int minuteNow = cal.get(Calendar.MINUTE);
			int secondNow = cal.get(Calendar.SECOND);
			if(countClick == 0 || (countClick < 3 && checkTime(minute, second, minuteNow, secondNow))){
				countClick ++;
				minute = minuteNow;
				second = secondNow;
			}
			else if(countClick == 3 ){
			DBSystem dbcv = new DBSystem(this);
			dbcv.open();
			dbcv.UpdateRemember("0");
			dbcv.close();
			Intent intent = new Intent(Main.this, LoginConfig.class);
			startActivity(intent);
			Main.this.finish();
			setValueClick();
			}else {
				setValueClick();
			}	
			break;
		}
	}
	

	/**
	 * @author Administrator save value default for Shared Prferrences
	 * @param nameIndex
	 * @param nameValue
	 * @param value
	 *            date 03/04/2014
	 */
	@SuppressLint("WorldReadableFiles")
	public void saveValueDefaultByString(String nameIndex, String nameValue,
			String value) {
		SharedPreferences sharePre = getSharedPreferences(nameIndex,
				MODE_WORLD_READABLE);
		SharedPreferences.Editor prefEditor = sharePre.edit();
		prefEditor.putString(nameValue, value);
		prefEditor.commit();
	}

	/**
	 * @author Administrator
	 * @param nameIndex
	 * @param type
	 * @param nameValue
	 *            clear value defualt for Shared Preferrences date 03/04/2014
	 */
	public void clearValueDefault(String nameIndex, int type, String nameValue) {
		SharedPreferences sharePre = getSharedPreferences(nameIndex,
				MODE_WORLD_READABLE);
		SharedPreferences.Editor prefEditor = sharePre.edit();
		if (type == 0)
			prefEditor.putString(nameValue, "");
		else
			prefEditor.putInt(nameValue, -1);
	}
	
	public Boolean connect (DBSystem dbHelper ){
		dbHelper = new DBSystem(this);
		dbHelper.open();
		Cursor cur = dbHelper.SelectSystemAll();
		String strServerNameWifi = "";
		String strServerPort = "";
		String strLogin = "";
		String strPassword = "";
		String strDatabaseName = "";
		String strRemember = "";
		String strChiNhanh = "";
		String strServerName3G = "";
		String strStatusServerName = "";
		if (cur != null) {
			while (cur.moveToNext()) {
				strServerNameWifi = cur.getString(1).toString();
				strServerPort = cur.getString(2).toString();
				strLogin = cur.getString(3).toString();
				strPassword = cur.getString(4).toString();
				strDatabaseName = cur.getString(5).toString();
				strRemember = cur.getString(6).toString();
				strChiNhanh = cur.getString(8).toString();
				strServerName3G = cur.getString(9).toString();
				strStatusServerName = cur.getString(10).toString();
			}
		}
		cur.close();
		try {
			if (strRemember.equals("1")) {
				if (strStatusServerName.equals("wifi")) {
					Global.ServerName = strServerNameWifi;
					Global.StatusServerName = "wifi";
				} else {
					Global.ServerName = strServerName3G;
					Global.StatusServerName = "3g";
				}
				Global.ServerPort = strServerPort;
				Global.Login = strLogin;
				Global.Password = strPassword;
				Global.DatabaseName = strDatabaseName;
				Global.ChiNhanh = strChiNhanh;
				String url = "jdbc:jtds:sqlserver://" + Global.ServerName + ":"
						+ strServerPort + "; DatabaseName=" + strDatabaseName
						+ ";integratedSecurity=true;user=" + strLogin
						+ ";password=" + strPassword + "";
				String driver = "net.sourceforge.jtds.jdbc.Driver";
				Class.forName(driver).newInstance();
				DriverManager.getConnection(url);
				dbHelper.close();
				return true;
			}
		} catch (Exception e) {
			dbHelper.close();
			return false;
		}
		return true;
	}
	public Boolean checkTime(int minutePrevious,int secondPrevious ,int minuteNow, int secondNow) {
		int timeOut = 0;
		Boolean check = true;
		if (minutePrevious < minuteNow) {
			timeOut = (60 - secondPrevious) + secondNow;
			if (timeOut > 30)
				check = false;
		} else if (minutePrevious == minuteNow) {
			timeOut = secondNow - secondPrevious;
			if (timeOut > 30)
				check = false;
		} else
			check = false;
		return check;
	}
	
	public void setValueClick() {
		countClick = 0;
		second = 0;
		minute = 0;
	}
}